/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
	This file is part of the OdinMS Maple Story Server
    Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc>
		       Matthias Butz <matze@odinms.de>
		       Jan Christian Meyer <vimes@odinms.de>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation version 3 as published by
    the Free Software Foundation. You may not use, modify or distribute
    this program under any other version of the GNU Affero General Public
    License.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
package client.command;

import java.sql.SQLException;
import server.maps.MapleMap;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.sql.PreparedStatement;
import client.MapleCharacter;
import client.MapleClient;
import tools.DatabaseConnection;
import tools.StringUtil;
import net.channel.ChannelServer;
import tools.MaplePacketCreator;

class Guardian {
    static boolean execute(MapleClient c, String[] splitted, char heading) throws SQLException {
        MapleCharacter player = c.getPlayer();
        ChannelServer cserv = c.getChannelServer();
        if (splitted[0].equals("smegaoff")) {
            MapleCharacter victim = cserv.getPlayerStorage().getCharacterByName(splitted[1]);
            victim.setCanSmega(false);
            player.dropMessage("You have disabled " + victim.getName() + "'s megaphone privilages");
            if (!(c.getPlayer().getName().equals(victim.getName()))) {
                victim.dropMessage("Your megaphone privilages have been disabled by a GM. If you continue to spam you will be temp. banned.");
            }

                    } else if (splitted[0].equals("jail")) {
            MapleCharacter victim = cserv.getPlayerStorage().getCharacterByName(splitted[1]);
            if(victim.gmLevel() >= player.gmLevel())
            {
                player.dropMessage("You can't jail a GM with a higher GM level than you!");
            }
            else if(victim.getAdmin())
            {
                player.Jail();
            }
            else
            {
                victim.Jail();
            }
        }  else if (splitted[0].equals("say")) {
            try {
                cserv.getWorldInterface().broadcastMessage(player.getName(), MaplePacketCreator.serverNotice(6, player.getName() + ": " + joinStringFrom(splitted, 1)).getBytes());
            } catch (Exception e) {
                cserv.reconnectWorld();
            }
         }
        else if (splitted[0].equals("cancelbuffs")) {
            MapleCharacter victim = cserv.getPlayerStorage().getCharacterByName(splitted[1]);
            if(victim.gmLevel() > player.gmLevel())
            {
                if(victim.gmLevel() == 5)
                player.cancelAllBuffs();
                else
                player.dropMessage("You can't cancelbuffs a GM with an equal or higher GM level!");
            }
            else
            {
                victim.cancelAllBuffs();
            }
            victim.cancelAllBuffs();
        } else if (splitted[0].equals("unjail")) {
            MapleCharacter victim = cserv.getPlayerStorage().getCharacterByName(splitted[1]);
            victim.Unjail();
        } else if (splitted[0].equals("smegaon")) {
            MapleCharacter victim = cserv.getPlayerStorage().getCharacterByName(splitted[1]);
            victim.setCanSmega(true);
            player.dropMessage("You have enabled " + victim.getName() + "'s megaphone privilages");
            if (!(c.getPlayer().getName().equals(victim.getName()))) {
                victim.dropMessage("Your megaphone privilages have been enabled by a GM. Please remember not to spam.");
            }

        else if (splitted[0].equals("id"))
            try {
                BufferedReader dis = new BufferedReader(new InputStreamReader(new URL("http://www.mapletip.com/search_java.php?search_value=" + splitted[1] + "&check=true").openConnection().getInputStream()));
                String s;
                while ((s = dis.readLine()) != null)
                    player.dropMessage(s);
                dis.close();
            } catch (Exception e) {
            }

            } else if (splitted[0].equals("charinfo")) {
            StringBuilder builder = new StringBuilder();
            MapleCharacter other = c.getChannelServer().getPlayerStorage().getCharacterByName(splitted[1]);

            builder.append(other.getName());
            builder.append(" at ");
            builder.append(other.getPosition().x);
            builder.append("/");
            builder.append(other.getPosition().y);
            builder.append(" ");
            builder.append(other.getHp());
            builder.append("/");
            builder.append(other.getCurrentMaxHp());
            builder.append("hp ");
            builder.append(other.getMp());
            builder.append("/");
            builder.append(other.getCurrentMaxMp());
            builder.append("mp ");
            builder.append(other.getExp());
            builder.append("exp hasParty: ");
            builder.append(other.getParty() != null);
            builder.append(" hasTrade: ");
            builder.append(other.getTrade() != null);
            builder.append(" remoteAddress: ");
            builder.append(other.getClient().getSession().getRemoteAddress());
            c.getPlayer().dropMessage(builder.toString());
        }  else if (splitted[0].equals("tele")) {
            MapleCharacter victim = cserv.getPlayerStorage().getCharacterByName(splitted[1]);
            if (victim != null) {
                if (splitted.length == 2) {
                    MapleMap target = victim.getMap();
                    c.getPlayer().changeMap(target, target.findClosestSpawnpoint(victim.getPosition()));
                } else {
                    int mapid = Integer.parseInt(splitted[2]);
                    MapleMap target = ChannelServer.getInstance(c.getChannel()).getMapFactory().getMap(mapid);
                    if(victim.gmLevel() >= player.gmLevel())
                    {
                        player.dropMessage("You can't warp to a GM with an equal or higher GM level!");
                    }
                    else if(victim.getAdmin())
                    {
                        player.changeMap(target, target.getPortal(0));
                    }
                    else
                        victim.changeMap(target, target.getPortal(0));
                }
            }
        } else if (splitted[0].equals("kill")) {
             MapleCharacter victim = cserv.getPlayerStorage().getCharacterByName(splitted[1]);
            if(victim.gmLevel() >= player.gmLevel())
            {
                if(victim.getAdmin())
                    player.setHpMp(0);
            }
                else
            {
            victim.setHpMp(0);
            }
        } else if (splitted[0].equals("mute")) {
            MapleCharacter victim = cserv.getPlayerStorage().getCharacterByName(splitted[1]);
            if(victim.gmLevel() > player.gmLevel())
            {
                if(victim.gmLevel() == 5)
                player.setMute();
            }
                else
            {
            victim.setMute();
            if(victim.getMute() == 1 || victim.getMute() == 2)
            {
            victim.dropMessage("You have been muted by a GM!");
            player.dropMessage(victim.getName() + " has been muted.");
            }
            }
        } else if (splitted[0].equals("dc")) {
            int level = 0;
            MapleCharacter victim;
            if (splitted[1].charAt(0) == '-') {
                level = StringUtil.countCharacters(splitted[1], 'f');
                victim = cserv.getPlayerStorage().getCharacterByName(splitted[2]);
            } else {
                victim = cserv.getPlayerStorage().getCharacterByName(splitted[1]);
            }
            if(victim.gmLevel() < player.gmLevel())
            {
                {
                    if (level >= 1) {
                        victim.getClient().disconnect();
                    };
                    if (level >= 2) {
                        victim.saveToDB(true);
                        cserv.removePlayer(victim);
                    }
                    victim.getClient().getSession().close();
                    return true;
                }
            }
            else if(victim.getAdmin())
            {
                player.getClient().getSession().close();
            }
            else
            {
                player.dropMessage("You can't dc a GM with a higher GM level than you!");
            }


        }
 else if (splitted[0].equals("unmute"))
        {
     MapleCharacter victim = cserv.getPlayerStorage().getCharacterByName(splitted[1]);
     if(victim.getMute() != 0) {
     victim.dropMessage("You have been unmuted by a GM, please don't repeat the reason why you were muted in the future!");
     player.dropMessage(victim.getName() + " has been unmuted.");
     victim.setUnmute();
        }
 else if(victim.getMute() == 0)
     {
         player.dropMessage(victim.getName() + " is not muted.");
 }

        } else if (splitted[0].equals("ban")) {

            if (splitted.length < 3) {
                player.dropMessage("Syntax for !ban: !ban user reason");
                return false;
            }
            String originalReason = StringUtil.joinStringFrom(splitted, 2);
            String reason = c.getPlayer().getName() + " banned " + splitted[1] + ": " + originalReason;
            MapleCharacter target = cserv.getPlayerStorage().getCharacterByName(splitted[1]);
            if (target != null) {
                if(target.gmLevel() <= 2)
                {
                String readableTargetName = MapleCharacter.makeMapleReadable(target.getName());
                String ip = target.getClient().getSession().getRemoteAddress().toString().split(":")[0];
                reason += " (IP: " + ip + ")";
                target.ban(reason, true);
                player.dropMessage("Banned " + readableTargetName + " ipban for " + ip + " reason: " + originalReason);
                }
                else
                {
                    player.dropMessage("You can't ban a GM!");
                }
            } else {
                if (MapleCharacter.ban(splitted[1], reason, false)) {
                    player.dropMessage("Offline Banned " + splitted[1]);
                } else {
                    player.dropMessage("Failed to ban " + splitted[1]);
                }
            }
            return true;
        }
       else if (splitted[0].equals("onlinechan")) {
            String s = "Characters online (" + cserv.getPlayerStorage().getAllCharacters().size() + ") : ";
            for (MapleCharacter chr : cserv.getPlayerStorage().getAllCharacters())
                s += MapleCharacter.makeMapleReadable(chr.getName()) + ", ";
            player.dropMessage(s.substring(0, s.length() - 2));
        }  else if (splitted[0].equals("servermessage"))
        {
            for (int i = 1; i <= ChannelServer.getAllInstances().size(); i++)
                ChannelServer.getInstance(i).setServerMessage(joinStringFrom(splitted, 1));
        } else {
            return false;
        }
        return true;
    }

    static String joinStringFrom(String arr[], int start) {
        StringBuilder builder = new StringBuilder();
        for (int i = start; i < arr.length; i++) {
            builder.append(arr[i]);
            if (i != arr.length - 1)
                builder.append(" ");
        }
        return builder.toString();
    }

    private static int getNoticeType(String typestring) {
		if (typestring.equals("n")) {
			return 0;
		} else if (typestring.equals("p")) {
			return 1;
		} else if (typestring.equals("l")) {
			return 2;
		} else if (typestring.equals("nv")) {
			return 5;
		} else if (typestring.equals("v")) {
			return 5;
		} else if (typestring.equals("b")) {
			return 6;
		}
		return -1;
	}
}

